package com.sina.interfaces.dao.user;

import com.sina.interfaces.dao.InterFacesDataSourceDao;
import com.sina.interfaces.domain.user.User_;
import com.sina.interfaces.domain.user.User;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2017-09-21-10:34
 */
@Repository("userDao")
public class UserDaoImpl extends InterFacesDataSourceDao implements UserDao {
    @Override
    public List<Map<String, Object>> getUserList(User criteria) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<User> root = criteriaQuery.from(User.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    userSelection(root)
            );

            Predicate predicate = findUserPredicate(criteria, builder, root);
            //指定查询条件
            criteriaQuery.where(predicate);
            boolean hasLastId = criteria.getLastId() != null;
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.desc(root.get(User_.id))
            );
            //创建查询
            org.hibernate.query.Query<Tuple> query = session.createQuery(criteriaQuery);

            if (!hasLastId) {
                int first = (criteria.getPage() - 1) * criteria.getRows();
                query.setFirstResult(first);
            }
            query.setMaxResults(criteria.getRows());
            //执行查询 query.getResultList()
            //将结果集转化为map对象  如果传入List.class则转化为list
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    @Override
    public long getUserCount(User criteria) {
        return template.executeWithNativeSession(session -> {

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<User> root = criteriaQuery.from(User.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(User_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    findUserPredicate(criteria, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }

    @Override
    public User getUserByNameAndPassword(String name, String password) {
        return unique("from User where name=:name and password=:password",
                new String[]{"name", "password"},
                new Object[]{name, password});
    }

    protected List<Selection<?>> userSelection(Root<User> root) {
        List<Selection<?>> list = new ArrayList<>(33);

        list.add(root.get(User_.id).alias("id"));
        list.add(root.get(User_.name).alias("name"));
        list.add(root.get(User_.password).alias("password"));
        list.add(root.get(User_.userSex).alias("userSex"));

        list.add(root.get(User_.createTime).alias("createTime"));
        list.add(root.get(User_.lastIp).alias("lastIp"));

        return list;

    }

    protected Predicate findUserPredicate(User criteria, CriteriaBuilder builder
            , Root<User> root) {
        List<Predicate> list = new ArrayList<>(3);

        if (criteria.getLastId() != null) {
            list.add(
                    builder.lt(root.get(User_.id), criteria.getLastId())
            );
        }

        //记录id
        if (criteria.getId() != null) {
            list.add(
                    builder.equal(root.get(User_.id), criteria.getId())
            );
        }


        //在指定时间内  包含端点时间
        if (criteria.getCreateStart() != null) {
            list.add(
                    builder.greaterThanOrEqualTo(root.get(User_.createTime), criteria.getCreateStart())
            );
        }

        if (criteria.getCreateEnd() != null) {
            list.add(
                    builder.lessThanOrEqualTo(root.get(User_.createTime), criteria.getCreateEnd())
            );
        }

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }

}
